import { Provide, Inject } from '@midwayjs/core';
import { PrismaService } from './prisma.service';

interface WechatUserInfo {
  openid: string;
  nickname: string;
  sex: number;
  province: string;
  city: string;
  country: string;
  headimgurl: string;
  privilege: string[];
  unionid?: string;
}

@Provide()
export class UserService {
  @Inject()
  prisma: PrismaService;

  /**
   * 根据微信用户信息查找或创建用户
   * @param userInfo 从微信获取的用户信息
   */
  async findOrCreateUserByWechat(userInfo: WechatUserInfo) {
    const { openid, nickname, headimgurl, unionid } = userInfo;

    let user = await this.prisma.user.findUnique({
      where: { openid },
    });

    if (user) {
      // 如果用户已存在，更新信息
      user = await this.prisma.user.update({
        where: { openid },
        data: {
          nickname,
          avatar: headimgurl,
          unionid,
        },
      });
    } else {
      // 如果用户不存在，创建新用户
      user = await this.prisma.user.create({
        data: {
          openid,
          nickname,
          avatar: headimgurl,
          unionid,
        },
      });
    }

    return user;
  }
}
